package com.ht.api.call.impl;

import java.util.List;

import org.springframework.stereotype.Component;

import com.ht.api.bean.AjaxResult;
import com.ht.api.bean.LoginBean;
import com.ht.api.call.AbstractCall;
import com.ht.api.db.Db;
import com.ht.api.db.DbConfig;
import com.ht.api.db.Entity;
import com.ht.api.db.StreamLoadConfig;
import com.ht.api.db.exception.HtException;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

/**
 * 业务执行器:batch
 * @author asq
 * @createTime 2024年12月23日 21:02:18
 */
@Component
public class BatchCall extends AbstractCall {
	
	@Override
	public boolean isOpen() {
		return false;
	}

	@Override
	public String getName() {
		return "通用批量新增";
	}

	@Override
	public AjaxResult doExecute(LoginBean me, JSONObject param, JSONObject config) {
		String table = config.getStr("table");

		StreamLoadConfig streamLoadConfig = null;
		if (me.isSysCommonCall()) {
			streamLoadConfig = DbConfig.useSysSLC();
		} else {
			streamLoadConfig = me.getStreamLoadConfig();
		}


		Object paramObj = param.get(PARAM);
		if (paramObj instanceof JSONArray) {
			List<Entity> list = JSONUtil.toList((JSONArray)paramObj, Entity.class);
			list.stream().forEach(b -> b.setTable(table).set("sys_creator", me.getLoginId()));
			Db.insertBatchWithStream(streamLoadConfig, list);
		} else {
			throw new HtException(String.format("%s字段必须为JSONArray数组~", PARAM));
		}
		return AjaxResult.success();
	}

}
